//
//  JsBridgeViewController.m
//  weex
//
//  Created by mac on 2017/8/24.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "JsBridgeViewController.h"

#import "WebViewJavascriptBridge.h" 
#import "NetWorkHelper.h"
#import "DataSyncHelper.h"

@interface JsBridgeViewController (){
    NetWorkHelper *netWorkHelper;
}
@property WebViewJavascriptBridge* bridge;
@property XFAudioHelper *XFAudioHelper;

@property (nonatomic, strong) WKWebView *wkWebView;

@end

UIWebView *webView;

@implementation JsBridgeViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    NSString* path = [[NSBundle mainBundle] pathForResource:@"html/jsbridge" ofType:@"html"];
    NSURL* url = [NSURL fileURLWithPath:path];
    NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
    
   // NSURL* url = [NSURL URLWithString:@"http://playschool.yun.c2d.me/test/demo/index.html"];//创建URL
   // NSURLRequest* request = [NSURLRequest requestWithURL:url];//创建NSURLRequest
    
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [webView loadRequest:request];
    [self.view addSubview:webView];
    
    
    
    //js桥
    _bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
    _XFAudioHelper = [[XFAudioHelper alloc]init];
    _XFAudioHelper.delegate = self;//设置委托,onResult回调才能起作用
    //注册函数testObjcCallback供js调用
    [self registerHandler];
    //取消webview的弹性滑动
    [(UIScrollView *)[[webView subviews] objectAtIndex:0] setBounces:NO];
    
    //异步处理数据同步
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 处理耗时操作的代码块...
        DataSyncHelper *sync = [[DataSyncHelper alloc]init];
        [sync sync:^(BOOL res) {
            
        }];
        //通知主线程刷新
        /*dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            NSLog(@"处理完成");
        });*/
        
    });
    
    
    
    

    
}

/**
 * 注册函数testObjcCallback供js调用
 */
-(void)registerHandler{
    netWorkHelper = [[NetWorkHelper alloc]initWithUrl:@""];
    //get请求
    [_bridge registerHandler:@"network-get" handler:^(NSDictionary *param, WVJBResponseCallback responseCallback) {
        if(param == nil){
            return;
        }
        NSString *cacheKey = [param objectForKey:@"cacheKey"];
        NSString *url = [param objectForKey:@"url"];
        if(cacheKey != nil){//需要设置缓存
            [netWorkHelper GET:url cacheKey:cacheKey completion:^(BOOL success, NSDictionary *data) {
                //处理你的请求
                data = data == NULL ? @{} : data;
                NSString *res = success == true ? @"true" : @"false";
                NSDictionary *dic2 = @{@"success":res,@"result":data};
                responseCallback(dic2);
            }];
        }else{//不需要缓存
            
            [netWorkHelper GET:url completion:^(BOOL success, NSDictionary *data) {
                //处理你的请求
                data = data == NULL ? @{} : data;
                NSString *res = success == true ? @"true" : @"false";
              
                NSDictionary *dic2 = @{@"success":res,@"result": data};
                responseCallback(dic2);
            }];
        }
    }];
    
    //post请求
    [_bridge registerHandler:@"network-post" handler:^(NSDictionary *param, WVJBResponseCallback responseCallback) {
        if(param == nil){
            return;
        }
        NSString *cacheKey = [param objectForKey:@"cacheKey"];
        NSString *url = [param objectForKey:@"url"];
        NSDictionary *params = [param objectForKey:@"params"];
        NSLog(@"%@",params);
        if(cacheKey != nil){//需要设置缓存
            [netWorkHelper POST:url cacheKey:cacheKey params:params compile:^(BOOL success, NSDictionary *data) {
                //处理你的请求
                data = data == NULL ? @{} : data;
                NSString *res = success == true ? @"true" : @"false";
                NSDictionary *dic2 = @{@"success":res,@"result":data};
                responseCallback(dic2);
            }];
        }else{//不需要缓存
            [netWorkHelper POST:url params:params completion:^(BOOL success, NSDictionary *data) {
                //处理你的请求
                data = data == NULL ? @{} : data;
                NSString *res = success == true ? @"true" : @"false";
                NSDictionary *dic2 = @{@"success":res,@"result": data};
                responseCallback(dic2);
            }];
        }
    }];
    //其它操作
    [_bridge registerHandler:@"network-operation" handler:^(NSDictionary *param, WVJBResponseCallback responseCallback) {
        if(param == nil){
            responseCallback(@"error");
            return;
        }
        NSString *operation = [param objectForKey:@"operation"];
        if ([operation isEqualToString:@"cancel_all_request"]) {//取消全部网络请求
            [netWorkHelper cancelAllOperations];
        }else if([operation isEqualToString:@"remove_cache_key"]){//移除指定缓存
            [netWorkHelper removeKeyCache:[param objectForKey:@"cacheKey"]];
        }else if([operation isEqualToString:@"remove_cache_all"]){//移除全部缓存
            [netWorkHelper removeAllCache];
        }
        responseCallback(@"success");
     }];
    //讯飞语音
    [_bridge registerHandler:@"xf-helper" handler:^(NSDictionary *param, WVJBResponseCallback responseCallback) {
        NSString *operation = [param objectForKey:@"operation"];
        if ([operation isEqualToString:@"build"]) {
            [_XFAudioHelper build];
        }else if([operation isEqualToString:@"start"]){
            [_XFAudioHelper start_record];
        }else if([operation isEqualToString:@"stop"]){
            [_XFAudioHelper stop_record];
        }else if([operation isEqualToString:@"dealloc"]){
            [_XFAudioHelper dealloc_audio];
        }
        responseCallback(@"success");
    }];
    
}


-(void) onResult:(BOOL) success results:(NSString *)results{
    //NSLog(@"%@",NSStringFromClass([XFCallback class]));
    NSDictionary *result = @{@"success":success==true?@"true":@"false",@"results":results};
    [_bridge callHandler:@"xf-result" data:result responseCallback:^(id response) {
        //NSLog(@"testJavascriptHandler responded: %@", response);
    }];
}


//设置状态栏颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


//强制横屏
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_9_0
- (NSUInteger)supportedInterfaceOrientations
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
#endif
{
    return UIInterfaceOrientationMaskLandscape;
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
}



@end
